package cn.tedu._03vehicle.base.filters;

import cn.tedu._03vehicle.pojo.vo.UserVO;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
/**
 * 登录检查过滤器
 */

@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = {"/v1/vehicle/*"})
public class LoginCheckFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.debug("初始化过滤器...");
    }

    /**
     * 过滤器的核心方法
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.debug("进入登录状态校验的过滤器...");
        /*
            1.获取session对象;
            2.从session对象中获取当前登录的用户UserVO;
            3.判断用户是否登录;
            4.如果用户未登录，则跳转到登录页面;
            5.如果用户已登录，则放行，继续执行下一个过滤器或者目标资源;
         */
        // 父类需要用到子类的方法,所以需要进行类型转换;
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        HttpSession session = request.getSession();
        UserVO userVO = (UserVO) session.getAttribute("user");
        if (userVO != null){//已登录,放行
            //有此行代码,代表放行;
            //无此行代码,代表拦截;
            filterChain.doFilter(request, response);
        } else {//未登录,拦截
            response.sendRedirect("/login.html");
        }
    }

    @Override
    public void destroy() {
        log.debug("过滤器销毁时执行的方法...");
    }
}
